package com.bw.controller;

import com.alibaba.fastjson2.JSON;
import com.bw.domain.Role;
import com.bw.domain.TbMenu;
import com.bw.service.RoleService;
import com.bw.utils.MenuUtil;
import com.bw.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;

/**
 * @Author: TaoShiHao
 * @Date: 2025/3/12 19:39
 * @Description:
 **/
@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    RoleService roleService;


    @RequestMapping("toadd")
    public String toadd(Model model){
        List<TbMenu> tbMenuList=roleService.listMenu();
        List<TbMenu> menuList = MenuUtil.treeMenus(tbMenuList, null);
        model.addAttribute("menuList", JSON.toJSON(menuList));
        return "/role/add";
    }
    @ResponseBody
    @RequestMapping("addOrUpdate")
    public R addOrUpdate(Role role,String menuIds){
        boolean b =roleService.addOrUpdate(role,menuIds);
        return b?R.OK():R.ERROR(500,"操作失败");
    }
    @ResponseBody
    @RequestMapping("checkRoleName")
    public R checkRoleName(String roleName){
       Role role= roleService.checkRoleName(roleName);
       //如果该角色存在 查询当前角色拥有的权限
        List<Integer> menuIds=null;
        HashMap<String, Object> map = new HashMap<>();

       if(role!=null){
         menuIds= roleService.getMenuIdByRoleId(role.getId());
           map.put("roleId",role.getId());
           map.put("menuIds",menuIds);
       }


        return role!=null? R.OK(map):R.ERROR(500,"角色不存在");
    }
}
